<script lang="ts" setup>
import { onHide, onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { nextTick, reactive, ref, watch } from 'vue';
import { getBothChatListApi, sendMessageApi } from '../../../api/chat';
import { getUserInfoApi } from '../../../api/user';

// uid是当前登录用户id,fromid是某个点击的用户id
import { useUserStore } from '../../../stores/modules/user';

const userStore = useUserStore()
//第一种接参方法，适合搭配TS
const query = defineProps<{
  fromId: string
  userName: string
}>()

//获取点击的用户的信息
const otherUserInfo = ref({})
const getOtherUserInfo = async () => {
  const res = await getUserInfoApi(query.fromId)
  otherUserInfo.value  = res.data
}

//获取当前登录用户的信息
const selfUserInfo = ref({})
const getSelfUserInfo = async () => {
  const res = await getUserInfoApi(userStore.userInfo.id)
  selfUserInfo.value  = res.data
}

//获取双方用户聊天记录
const BothChatList = ref([])
const getBothChatList = async () => {
  const res = await getBothChatListApi(userStore.userInfo.id,query.fromId)
  BothChatList.value = res.data
}

//第二种接参
onLoad((option) => {
  //修改tab变成用户名
  if(userStore.userInfo.id === +query.fromId){
    uni.setNavigationBarTitle({
    title: '文件传输助手',
  })} else{
    uni.setNavigationBarTitle({
    title: option.userName,
  })}
  Promise.all([getBothChatList(),getOtherUserInfo(),getSelfUserInfo()])
  uni.onSocketOpen((res) => {
  console.log('WebSocket已打开');
  });
}) 

//滚轮到最底部
let toId = ref('')
watch(BothChatList,(newval)=>{
nextTick(()=>{
	toId.value = "toId-" + (newval.length - 1)
})
},{
	deep:true, //深度监视
	immediate:true //初始化立即执行
})



const text = ref('')
const chatFrom = reactive({
  userId: null,
  fromId: userStore.userInfo.id,
  types: '0',
  message: ' '
})

//发送消息
const send = async () => {
  if(text.value.trim().length !== 0){
  chatFrom.message =text.value
  chatFrom.userId = otherUserInfo.value.id
  //webSock发送消息
  sendSocketMessage(JSON.stringify(chatFrom))
  await sendMessageApi(JSON.stringify(chatFrom))
  text.value = ''
  await getBothChatList()
  }
}

//webSoket连接
uni.connectSocket({
  url: 'ws://192.168.145.227:3333/websocket/'+ userStore.userInfo.id
});

//websoket发送消息
const sendSocketMessage = (msg) => {
  
    uni.sendSocketMessage({
      data: msg,
      success: (result) => {console.log("消息发送成功");
      },
      fail: (error) => {console.log("消息发送失败");}
    })
  //  else {
  //   // socketMsgQueue.push(msg);
  // }
}
//websoket接收消息
uni.onSocketMessage((res) =>{
      console.log("收到服务器数据====" + res.data)
      if(JSON.parse(res.data).messageType === 4){
        BothChatList.value.push(JSON.parse(res.data));
      }
})

onUnload(() => {
  uni.onSocketClose(() =>{
		console.log("websocket已关闭");
	});
})
</script>

<template>
    <scroll-view scroll-with-animation :scroll-into-view="toId" class="scroll" scroll-y="true">
      <div class="chatBox">
        <template v-for="(item,index) in BothChatList" >
          <view :key="item.id" :id="`toId-${index}`" v-if="item.userId !== item.fromId && item.fromId === +query.fromId">
          <view class="chat-item">
            <view class="content-wrapper-left">
          <image :src="otherUserInfo.avatar" class="avator"></image>
          <view class="chat-content-left" v-if="item.types === '0'">{{item.message}}</view>
          </view>
          </view>
          </view>
          <view v-else :id="`toId-${index}`">
          <view class="chat-item">
            <view class="content-wrapper-right">
              <image :src="selfUserInfo.avatar" class="avator avator-right"></image>
              <view class="chat-content-right" v-if="item.types === '0'">{{item.message}}</view>
            </view>
          </view>
          </view>
        </template>
      </div>  
    </scroll-view>
    <div class="inputBox" >
      <uni-icons color="green" type="reload" size="10vw"></uni-icons>
      <uni-icons color="red" type="gift-filled" size="10vw"></uni-icons>
      <view class="b">
        <input v-model="text" type="text" class="input" placeholder="Send Message"> 
        <uni-icons @tap="send" color="green" class="sendIcon" type="paperplane-filled" size="10vw"></uni-icons>
      </view>
      <uni-icons color="blue" type="videocam-filled" size="10vw"></uni-icons>
    </div>

</template>

<style scoped lang="less">

.chat-item{
  width: 100%;
  height: 100%;
  margin: 5px;
  .content-wrapper-left{
    display: flex;
    position: relative;
    .chat-content-left{
      height: auto;
      max-width: 70%;
      margin: 10px;
      padding: 5px;
      word-wrap: break-word;
      background-color: skyblue;
      border-radius:10px;
      font-size: 1.5rem;
    }
  }
  .content-wrapper-right{
    display: flex;
    flex-direction: row-reverse;
    padding-right: 10px;
    position: relative;
    .chat-content-right{
      height: auto;
      max-width: 70%;
      margin: 10px;
      padding: 5px;
      word-wrap: break-word;
      background-color: skyblue;
      border-radius: 10px;
      font-size: 1.5rem;
    }
  }
}
.avator{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.content-wrapper-left::after{
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  /* 箭头靠左边 */
  top: 16px;
  left: 50px;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid skyblue;
}
.content-wrapper-right::after{
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  /* 箭头靠右边 */
  top: 16px;
  right: 60px;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid skyblue;
}
.box{
  height: 100%;
}
// #ifdef H5
.scroll{
  height: 86vh;
}
// #endif

.scroll{
  height: 90vh;
}


.inputBox{
  position: fixed;
  bottom: -0.1rem;
  background-color: #fefefe;
  height: 19vw;
  width: 100%;
  border-top: 3px solid #f6f6f6;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.input{
  background-color: #fafafa;
  border-radius: 10px;
  max-width:100%;
  height: 10vw;
  color: black;
  padding-left: 1rem;
  padding-right: 3rem;
  font-size: 1rem;
}
.b{
  display: flex;
  position: relative;
}
.sendIcon{
  position: absolute;
  right: 3%;
  line-height: 10vw;
}


</style>